package net.kesumu.yushabu;

import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Locale;

import net.kesumu.general.android.EasyStorage.EasyStorage;
import net.kesumu.general.android.view.CustomStatusBar;
import net.kesumu.yushabu.storage.FriendDbOperator;
import net.kesumu.yushabu.utils.JSONUtil;
import net.kesumu.yushabu.utils.WsConfig;
import net.kesumu.yushabuserver.entity.User;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.codebutler.android_websockets.WebSocketClient;
import com.umeng.message.PushAgent;

public class FriendSearchActivity extends Activity {
    
    private EasyStorage mEasyStorage;
    
    String mFriendKeyWord;
    
    String mMyId;
    String mUserId;
    String mUserName;
    
    ArrayList<User> mFriendList;
    FriendSearchAdapter mFriendSearchAdapter;
    
    ArrayList<ImageView> mPhotoViews = new ArrayList<ImageView>();

    
    BroadcastReceiver broadcastReciever_image = new BroadcastReceiver() {
        public void onReceive(android.content.Context context, Intent intent) {
            String location = intent.getExtras().getString("location");
            if(location == null || location.length() == 0) {
//                pd.dismiss();
//                Toast.makeText(context, "Failed to download image", Toast.LENGTH_SHORT).show();
                return;
            }

                //Others' photo

           String photoName = location.substring(0, location.indexOf("."));
//          showToast("mMyPhotoName: "+ mMyPhotoName);
           String photoExtention = location.substring(location.indexOf(".")+1);
//          showToast("mMyPhotoExtention: "+ mMyPhotoExtention);
           Bitmap photo = mEasyStorage.getImageBitmap(photoName, photoExtention);
           for(int i=0;i<mPhotoViews.size();i++) {
               String yuyuChatId = mPhotoViews.get(i).getTag().toString();
               if(yuyuChatId!=null && yuyuChatId.equals(photoName)) {
                   mPhotoViews.get(i).setImageBitmap(photo);
               }
           }

//            Toast.makeText(context, "Download success", Toast.LENGTH_SHORT).show();
        };
    };
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_search);
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
        getActionBar().setCustomView(R.layout.actionbar);
        ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.title_activity_friend_search));
      //Custom the status bar
        CustomStatusBar customStatusBar = new CustomStatusBar(this);
        customStatusBar.setStatusBarColor(findViewById(R.id.statusBarBackground), getResources().getColor(R.color.main));

        
        
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new FriendSearchFragment()).commit();
        }
        
        mEasyStorage = new EasyStorage(this, getString(R.string.preference_file_key));
        mMyId = mEasyStorage.getString("mMyId");
        
        Intent receiveIntent = getIntent();
        mFriendKeyWord = receiveIntent.getStringExtra("friendKeyWord");
//        mMyId = receiveIntent.getStringExtra("myId");
        
        mFriendList = new ArrayList<User>();
        
        startUpClient();
        
        PushAgent.getInstance(this).onAppStart();
    }
    
    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_friend_search,
                    container, false);
            return rootView;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.friend_search, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
//        if (id == R.id.action_settings) {
//            return true;
//        }
        return super.onOptionsItemSelected(item);
    }
    
    public void searchFriend() {
        sendRequest(jsonUtil.getFriendSearchJSON(mMyId, mFriendKeyWord));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
         
        if(client != null & client.isConnected()){
            client.disconnect();
        }
    }

    /**
     * Connection with the server
     */
    private WebSocketClient client;
    private JSONUtil jsonUtil;
    void startUpClient() {
        if(client != null && client.isConnected()) {
            return;
        }
        jsonUtil = new JSONUtil(getApplicationContext());
        client = new WebSocketClient(URI.create(WsConfig.URL_WEBSOCKET
                + URLEncoder.encode(WsConfig.SESSION_TAG_DEFAULT)), new WebSocketClient.Listener() {
            public void onConnect() {
                searchFriend();
            }
            public void onMessage(String message) {
                parseMessage(message);
            }
            public void onMessage(byte[] data) {
                // Message will be in JSON format
                parseMessage(JSONUtil.bytesToHex(data));
            }
            public void onDisconnect(int code, String reason) {
                String message = String.format(Locale.US,
                        "Disconnected! Code: %d Reason: %s", code, reason);
                showToast(message);
            }
            public void onError(Exception error) {
                showToast("Error! : " + error);
            }
        }, null);
        client.connect();
    }

    //remove the null judge for immediately send a message after connection setup
    private void sendRequest(String message) {
        client.send(message);
    }
    
    private void parseMessage(final String msg) {
 
        try {
            JSONObject jObj = new JSONObject(msg);
 
            // JSON node 'flag'
            String flag = jObj.getString("flag");

            if (flag.equalsIgnoreCase(JSONUtil.FLAG_FRIEND_SEARCH)) {
                String result = jObj.getString("result");
                showToast(result);
                
                if(result != null && result.equalsIgnoreCase("success")) {
                
                    mUserId = jObj.getString("userId");
                    mUserName = jObj.getString("userName");
                    String yuyuChatId = jObj.getString("yuyuChatId");
                    
                    final User user = new User(Integer.parseInt(mUserId),mUserName, "", "", "", "");
                    user.setYuyuChatId(yuyuChatId);
    
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mFriendSearchAdapter.addItem(user);
                       }
                    });
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        findViewById(R.id.waiting).setVisibility(View.GONE);
                   }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    private void showToast(final String message) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), message,
                        Toast.LENGTH_SHORT).show();
            }
        });
 
    }
    
    /**
     * define the FriendAdapter class for friend list
     * @author Z 2014-12-16
     *
     */
    private class FriendSearchAdapter extends BaseAdapter{
        ArrayList<User> friendList = new ArrayList<User>();
        
        public void setData(ArrayList<User> fl) {
            this.friendList = fl;
            this.notifyDataSetChanged();
        }
        public int getCount() {
            if(friendList == null) {
                return 0;
            }else {
                return friendList.size();
            }
        }
        public Object getItem(int position) {
            if(friendList == null) {
                return null;
            }else{
                User friend = friendList.get(position);
                return friend;
            }
        }
        public long getItemId(int position) {
            return position;
        }
        public View getView(int position, View convertView, ViewGroup parent) {
            User friend = (User)getItem(position);
            ViewGroup listView = null;
            //Inflate a new view whatever
            listView = (ViewGroup)getLayoutInflater().inflate(R.layout.element_friend_search, null);
            
            TextView mFriendNameView = (TextView)listView.findViewById(R.id.text_name_friend);
            mFriendNameView.setText(friend.getName());
            TextView mFriendIdView = (TextView)listView.findViewById(R.id.text_id_friend);
            mFriendIdView.setText(friend.getUserId()+"");
            
            String friendYuYuChatId = friend.getYuyuChatId();
            //Remember this image view, then set downloaded image to it
            ImageView mFriendPhotoView = (ImageView) listView.findViewById(R.id.image_photo_friend);
            mFriendPhotoView.setTag(friendYuYuChatId);
            mPhotoViews.add(mFriendPhotoView);
            //Start intent service to download image
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ImageIntentService.DOWNLOAD_IMAGE);
            FriendSearchActivity.this.registerReceiver(broadcastReciever_image, intentFilter);
            Intent i = new Intent(FriendSearchActivity.this, ImageIntentService.class);
            i.putExtra("url", 
                    WsConfig.DOWNLOADIMG_HTTP
                    + friendYuYuChatId + ".jpg");
            i.putExtra("yuyuChatId", friendYuYuChatId);
            FriendSearchActivity.this.startService(i);
            
            /*String location = pixivPicture.location;
            if(location == null || location.length() == 0) {
              Toast.makeText(MainMenuActivity.this, "location error", Toast.LENGTH_SHORT).show();
              return null;
            }
            File imageFile = new File(location);
            if(!imageFile.exists()) {
                Toast.makeText(MainMenuActivity.this, "location file not found", Toast.LENGTH_SHORT).show();
                return null;
            }
            Bitmap bm = BitmapFactory.decodeFile(location);
            ImageView iv = (ImageView)listView.findViewById(R.id.picture_square);
            iv.setImageBitmap(bm);*/
            
            return listView;
        }
        
        public void addItem(final User item) {
            this.friendList.add(item);
            this.notifyDataSetChanged();
        }
    }
    
    /**
     * define the friend fragment for friend list
     * @author Z 2014-12-16
     *
     */
    @SuppressLint("ValidFragment")
    private class FriendSearchFragment extends ListFragment {   
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View fragment = inflater.inflate(R.layout.fragment_friend_search, container, false);
            mFriendSearchAdapter = new FriendSearchAdapter();
            for(int i=0; i<mFriendList.size(); i++) {
                mFriendSearchAdapter.addItem(mFriendList.get(i));
            }
            setListAdapter(mFriendSearchAdapter);
            return fragment;
        }
        
        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);
            Intent friendAcitivityIntent = new Intent(FriendSearchActivity.this,FriendActivity.class);
            User friend = (User) getListView().getItemAtPosition(position);
            friendAcitivityIntent.putExtra("userId", ""+friend.getUserId());
//            friendAcitivityIntent.putExtra("myId", mMyId);
            friendAcitivityIntent.putExtra("type", FriendActivity.TYPE_OTHERS);
            //This user is not friend, then has not friendPhotoPath
            //use yuyuChatId instead
            friendAcitivityIntent.putExtra("userPhotoPath", friend.getYuyuChatId()+".jpg");
            startActivity(friendAcitivityIntent);
        }
    }
    
}
